package com.bckj.fastboot.core.rpc.feign;

import com.bckj.fastboot.core.lang.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

@Slf4j
public class WebExceptionInterceptor implements HandlerExceptionResolver {

    public WebExceptionInterceptor() {
    }

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ExceptionResponse exceptionResponse = new ExceptionResponse();
        exceptionResponse.setMessage(ex.getMessage());
        exceptionResponse.setException(ex.getClass().getName());
        if (ex instanceof BusinessException) {
            log.debug("handleThrowable->response:{}", exceptionResponse);
        } else {
            log.error("handleThrowable->response:{}", exceptionResponse);
            log.error("exception", ex);
        }

        ModelAndView mv = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setExtractValueFromSingleKeyModel(true);
        mv.setView(view);
        mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        mv.addObject(exceptionResponse);
        return mv;
    }
}